#include "at32f435_437_board.h"
#include "at32f435_437_clock.h"
#include "usb_conf.h"
#include "usb_core.h"
#include "usbd_int.h"
#include "hid_iap_class.h"
#include "hid_iap_desc.h"
#include "hid_iap_user.h"
#include "cdc_class.h"
#include "cdc_desc.h"

#include "FreeRTOS.h"
#include "task.h"
#include "event_groups.h"

#include "rtos_bsp.h"

#include "u8g2_hal.h"
#include "u8g2.h"

#include "llcc68.h"
#include "llcc68_drive.h"

#include <string.h>

#define LED_ORANGE_ON()		gpio_bits_set(GPIOB, GPIO_PINS_12);
#define LED_ORANGE_OFF()	gpio_bits_reset(GPIOB, GPIO_PINS_12);

#define LED_GREEN_ON()		gpio_bits_set(GPIOB, GPIO_PINS_13);
#define LED_GREEN_OFF()		gpio_bits_reset(GPIOB, GPIO_PINS_13);

EventGroupHandle_t xLLCC68EventGroup;
u8g2_t u8g2;

extern i2c_handle_type hi2cB;

/* usb global struct define */
otg_core_type otg_core_struct;
otg_core_type otg2_core_struct;
void usb_clock48m_select(usb_clk48_s clk_s);
void usb_gpio_config(void);
void usb_low_power_wakeup_config(void);

/**
  * @brief  usb 48M clock select
  * @param  clk_s:USB_CLK_HICK, USB_CLK_HEXT
  * @retval none
  */
void usb_clock48m_select(usb_clk48_s clk_s)
{
  if(clk_s == USB_CLK_HICK)
  {
    crm_usb_clock_source_select(CRM_USB_CLOCK_SOURCE_HICK);

    /* enable the acc calibration ready interrupt */
    crm_periph_clock_enable(CRM_ACC_PERIPH_CLOCK, TRUE);

    /* update the c1\c2\c3 value */
    acc_write_c1(7980);
    acc_write_c2(8000);
    acc_write_c3(8020);
#if (USB_ID == 0)
    acc_sof_select(ACC_SOF_OTG1);
#else
    acc_sof_select(ACC_SOF_OTG2);
#endif
    /* open acc calibration */
    acc_calibration_mode_enable(ACC_CAL_HICKTRIM, TRUE);
  }
  else
  {
    switch(system_core_clock)
    {
      /* 48MHz */
      case 48000000:
        crm_usb_clock_div_set(CRM_USB_DIV_1);
        break;

      /* 72MHz */
      case 72000000:
        crm_usb_clock_div_set(CRM_USB_DIV_1_5);
        break;

      /* 96MHz */
      case 96000000:
        crm_usb_clock_div_set(CRM_USB_DIV_2);
        break;

      /* 120MHz */
      case 120000000:
        crm_usb_clock_div_set(CRM_USB_DIV_2_5);
        break;

      /* 144MHz */
      case 144000000:
        crm_usb_clock_div_set(CRM_USB_DIV_3);
        break;

      /* 168MHz */
      case 168000000:
        crm_usb_clock_div_set(CRM_USB_DIV_3_5);
        break;

      /* 192MHz */
      case 192000000:
        crm_usb_clock_div_set(CRM_USB_DIV_4);
        break;

      /* 216MHz */
      case 216000000:
        crm_usb_clock_div_set(CRM_USB_DIV_4_5);
        break;

      /* 240MHz */
      case 240000000:
        crm_usb_clock_div_set(CRM_USB_DIV_5);
        break;

      /* 264MHz */
      case 264000000:
        crm_usb_clock_div_set(CRM_USB_DIV_5_5);
        break;

      /* 288MHz */
      case 288000000:
        crm_usb_clock_div_set(CRM_USB_DIV_6);
        break;

      default:
        break;

    }
  }
}

/**
  * @brief  this function handles otgfs interrupt.
  * @param  none
  * @retval none
  */
void OTG_IRQ_HANDLER(void)
{
  usbd_irq_handler(&otg_core_struct);
}

void OTG2_IRQ_HANDLER(void)
{
  usbd_irq_handler(&otg2_core_struct);
}

/**
  * @brief  usb delay millisecond function.
  * @param  ms: number of millisecond delay
  * @retval none
  */
void usb_delay_ms(uint32_t ms)
{
  /* user can define self delay function */
  delay_ms_rtos(ms);
}

/**
  * @brief  usb delay microsecond function.
  * @param  us: number of microsecond delay
  * @retval none
  */
void usb_delay_us(uint32_t us)
{
  delay_us_rtos(us);
}

/**
  * @brief  this function config gpio.
  * @param  none
  * @retval none
  */
void usb_gpio_config(void)
{
	// otg1
  gpio_init_type gpio_init_struct;

  crm_periph_clock_enable(OTG_PIN_GPIO_CLOCK, TRUE);
  gpio_default_para_init(&gpio_init_struct);

  gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
  gpio_init_struct.gpio_out_type  = GPIO_OUTPUT_PUSH_PULL;
  gpio_init_struct.gpio_mode = GPIO_MODE_MUX;
  gpio_init_struct.gpio_pull = GPIO_PULL_NONE;

  /* dp and dm */
  gpio_init_struct.gpio_pins = OTG_PIN_DP | OTG_PIN_DM;
  gpio_init(OTG_PIN_GPIO, &gpio_init_struct);

  gpio_pin_mux_config(OTG_PIN_GPIO, OTG_PIN_DP_SOURCE, OTG_PIN_MUX);
  gpio_pin_mux_config(OTG_PIN_GPIO, OTG_PIN_DM_SOURCE, OTG_PIN_MUX);
	
	// otg2
  /* otg2 gpio config */
  crm_periph_clock_enable(OTG2_PIN_GPIO_CLOCK, TRUE);
  gpio_default_para_init(&gpio_init_struct);

  gpio_init_struct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
  gpio_init_struct.gpio_out_type  = GPIO_OUTPUT_PUSH_PULL;
  gpio_init_struct.gpio_mode = GPIO_MODE_MUX;
  gpio_init_struct.gpio_pull = GPIO_PULL_NONE;

  /* dp and dm */
  gpio_init_struct.gpio_pins = OTG2_PIN_DP | OTG2_PIN_DM;
  gpio_init(OTG2_PIN_GPIO, &gpio_init_struct);

  gpio_pin_mux_config(OTG2_PIN_GPIO, OTG2_PIN_DP_SOURCE, OTG2_PIN_MUX);
  gpio_pin_mux_config(OTG2_PIN_GPIO, OTG2_PIN_DM_SOURCE, OTG2_PIN_MUX);
}

void u8g2_disp_init(void)
{
	u8g2_i2c_init();
	u8g2_Setup_ssd1306_i2c_128x64_noname_f(
			&u8g2,
			U8G2_R0,
			u8x8_byte_i2c,
			u8x8_gpio_and_delay);  // init u8g2 structure
	u8x8_SetI2CAddress(&u8g2.u8x8, 0x78);

	u8g2_InitDisplay(&u8g2); // send init sequence to the display, display is in sleep mode after this,
	u8g2_SetContrast(&u8g2, 0xff);
	u8g2_SetPowerSave(&u8g2, 0); // wake up display
	u8g2_ClearBuffer(&u8g2);
	u8g2_ClearDisplay(&u8g2);
}

void llcc68_rx_task(void *pvParameters)
{
	uint32_t temp = 0;
	char tmr_buf1[32];
	
	xLLCC68EventGroup = xEventGroupCreate();
	
	llcc68_chip_init();
	llcc68_set_tx_cfg(0xff);
	
	uint64_t i = 0;
	while(1)
	{
		char send_msg[30];
		sprintf(send_msg, "send_msg=%03llu", i++);
		llcc68_send((uint8_t *)send_msg, strlen(send_msg));
		LED_ORANGE_OFF();
		EventBits_t uxBits;
		uxBits = xEventGroupWaitBits(
					xLLCC68EventGroup,   /* The event group being tested. */
					DIO_DONE_BIT, /* The bits within the event group to wait for. */
					pdTRUE,        /* BIT_0 & BIT_4 should be cleared before returning. */
					pdFALSE,       /* Don't wait for both bits, either bit will do. */
					pdMS_TO_TICKS(3000) );/* Wait a maximum of 100ms for either bit to be set. */
		
		llcc68_irq_mask_t llcc68_irq_mask;
		llcc68_get_and_clear_irq_status(NULL, &llcc68_irq_mask);
		if(uxBits & DIO_DONE_BIT)
		{
			LED_ORANGE_ON();
			
			// ERTC
			ertc_time_type time;
			ertc_calendar_get(&time);
			if(temp != time.sec)
			{
				sprintf(tmr_buf1, "%02d-%02d-%02d %02d:%02d:%02d",time.year, time.month, time.day,time.hour, time.min, time.sec);
				temp = time.sec;
			}
			
			// SHOW MESSAGE
			u8g2_ClearBuffer(&u8g2);
			u8g2_SetFont(&u8g2, u8g2_font_6x13_tf);
			u8g2_DrawStr(&u8g2, 0, 13, send_msg);
			//cdc_uart_print("%s\r\n", send_msg);
			
			// rx done
			if(llcc68_irq_mask & LLCC68_IRQ_TX_DONE)
			{
				u8g2_DrawStr(&u8g2, 0, 26, "TX_DONE");
				// printf("TX_DONE\r\n");
			}
			if(llcc68_irq_mask & LLCC68_IRQ_TIMEOUT)
			{
				u8g2_DrawStr(&u8g2, 0, 26, "TIMEOUT");
				// printf("TIMEOUT\r\n");
			}
			u8g2_DrawStr(&u8g2, 0, 64, tmr_buf1);
			u8g2_SendBuffer(&u8g2);
		}
		vTaskDelay(pdMS_TO_TICKS(50));
	}
	vTaskDelete(NULL);
}

void led_flashing_task(void *pvParameters)
{
	gpio_init_type gpio_initstruct;
	crm_periph_clock_enable(CRM_GPIOB_PERIPH_CLOCK, TRUE);
	
	gpio_default_para_init(&gpio_initstruct);
	gpio_initstruct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
	gpio_initstruct.gpio_mode = GPIO_MODE_OUTPUT;
	gpio_initstruct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL;
	gpio_initstruct.gpio_pins = GPIO_PINS_12 | GPIO_PINS_13;
	gpio_initstruct.gpio_pull = GPIO_PULL_NONE;
	
	gpio_init(GPIOB, &gpio_initstruct);
	LED_GREEN_ON();
	
//	while(1)
//	{
//		gpio_bits_write(GPIOB, GPIO_PINS_12, !gpio_output_data_bit_read(GPIOB, GPIO_PINS_12));
//		vTaskDelay(pdMS_TO_TICKS(100));
//		gpio_bits_write(GPIOB, GPIO_PINS_13, !gpio_output_data_bit_read(GPIOB, GPIO_PINS_13));
//		vTaskDelay(pdMS_TO_TICKS(100));
//	}
	
	vTaskDelete(NULL);
}

void iap_loop_task(void *pvParameters)
{
	while(1)
	{
		app_loop();
		vTaskDelay(pdMS_TO_TICKS(200));
	}
	vTaskDelete(NULL);
}

void app_main(void *pvParameters)
{
	u8g2_disp_init();
	
	eeprom_i2c_init();
	uint32_t rx_buf_boot_time;
	i2c_memory_read_dma(&hi2cB, I2C_MEM_ADDR_WIDIH_8, I2CB_ADDRESS, 0x00, (uint8_t *)&rx_buf_boot_time, 4, I2C_TIMEOUT);
	i2c_wait_end(&hi2cB, I2C_TIMEOUT);
	// inc boot time
	rx_buf_boot_time++;
	i2c_memory_write_dma(&hi2cB, I2C_MEM_ADDR_WIDIH_8, I2CB_ADDRESS, 0x00, (uint8_t *)&rx_buf_boot_time, 4, I2C_TIMEOUT);
	i2c_wait_end(&hi2cB, I2C_TIMEOUT);
	
	char boot_time_fmt[32];
	sprintf(boot_time_fmt, "BOOT TIME: %d", rx_buf_boot_time);
	
	u8g2_ClearBuffer(&u8g2);
	u8g2_SetFont(&u8g2, u8g2_font_6x13_tf);
	u8g2_DrawStr(&u8g2, 0, 26, "System Started");
	u8g2_DrawStr(&u8g2, 0, 36, boot_time_fmt);
	u8g2_SendBuffer(&u8g2);
	vTaskDelay(pdMS_TO_TICKS(3000));
	uart_printf("BOOT TIME: %d\r\n", rx_buf_boot_time);
	
	xTaskCreate(llcc68_rx_task, "app_main", 1024 * 2, NULL, 1, NULL);
	xTaskCreate(led_flashing_task, "led_flashing_task", 512, NULL, 1, NULL);
	xTaskCreate(iap_loop_task, "iap_loop_task", 512, NULL, 1, NULL);
	vTaskDelete(NULL);
}

/**
  * @brief  main function.
  * @param  none
  * @retval none
  */
int main(void)
{
	qspi_xip_config();
//	BOOTLOADER
	nvic_vector_table_set(NVIC_VECTTAB_FLASH, 0x5000);
	
	nvic_priority_group_config(NVIC_PRIORITY_GROUP_4);
  system_clock_config();

	iap_init();
	usb_gpio_config();
  /* enable otgfs clock */
  crm_periph_clock_enable(OTG_CLOCK, TRUE);
	crm_periph_clock_enable(OTG2_CLOCK, TRUE);
	
  /* select usb 48m clcok source */
  usb_clock48m_select(USB_CLK_HEXT);
  /* enable otgfs irq */
  nvic_irq_enable(OTG_IRQ, 0, 0);
	nvic_irq_enable(OTG2_IRQ, 0, 0);
  /* init usb */
  usbd_init(&otg_core_struct,
            USB_FULL_SPEED_CORE_ID,
            USB_ID,
            &hid_iap_class_handler,
            &hid_iap_desc_handler);
						
  /* init otg2 device */
  usbd_init(&otg2_core_struct,
            USB_FULL_SPEED_CORE_ID,
            USB2_ID,
            &cdc_class_handler,
            &cdc_desc_handler);
	
  //at32_board_init();
	uart_print_init(115200);
	uart_print_dma_init();
	delay_init_rtos();
	
	xTaskCreate(app_main, "app_main", 1024 * 8, NULL, 1, NULL);

	vTaskStartScheduler();
  while(1)
  {
  }
}

void vApplicationTickHook( void )
{
}

void vApplicationMallocFailedHook( void )
{
	/* vApplicationMallocFailedHook() will only be called if
	configUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h.  It is a hook
	function that will get called if a call to pvPortMalloc() fails.
	pvPortMalloc() is called internally by the kernel whenever a task, queue,
	timer or semaphore is created.  It is also called by various parts of the
	demo application.  If heap_1.c or heap_2.c are used, then the size of the
	heap available to pvPortMalloc() is defined by configTOTAL_HEAP_SIZE in
	FreeRTOSConfig.h, and the xPortGetFreeHeapSize() API function can be used
	to query the size of free heap space that remains (although it does not
	provide information on how the remaining heap might be fragmented). */
	taskDISABLE_INTERRUPTS();
	for( ;; );
}
/*-----------------------------------------------------------*/

void vApplicationIdleHook( void )
{
	/* vApplicationIdleHook() will only be called if configUSE_IDLE_HOOK is set
	to 1 in FreeRTOSConfig.h.  It will be called on each iteration of the idle
	task.  It is essential that code added to this hook function never attempts
	to block in any way (for example, call xQueueReceive() with a block time
	specified, or call vTaskDelay()).  If the application makes use of the
	vTaskDelete() API function (as this demo application does) then it is also
	important that vApplicationIdleHook() is permitted to return to its calling
	function, because it is the responsibility of the idle task to clean up
	memory allocated by the kernel to any task that has since been deleted. */
}
/*-----------------------------------------------------------*/

void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
{
	( void ) pcTaskName;
	( void ) pxTask;

	/* Run time stack overflow checking is performed if
	configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2.  This hook
	function is called if a stack overflow is detected. */
	taskDISABLE_INTERRUPTS();
	for( ;; );
}
/*-----------------------------------------------------------*/